package com.yunhoo.govProcure.bean;

import com.ibatis.dao.client.DaoManager;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.yunhoo.asset.model.Asset;
import com.yunhoo.base.model.AssetGBCode;
import com.yunhoo.govProcure.db.dao.ProcureExecEditDao;
import com.yunhoo.govProcure.model.CateEditBase;
import com.yunhoo.govProcure.model.CateEditDetail;
import com.yunhoo.govProcure.model.ExecuteAppend;
import com.yunhoo.sys.db.config.DaoConfig;
import com.yunhoo.sys.db.util.IbatisTemplate;
import com.yunhoo.sys.util.common.LoginParam;
import com.yunhoo.sys.util.common.ToolKit;
import com.yunhoo.sys.util.tree.TreeUtil;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import org.richfaces.event.TreeSelectionChangeEvent;
/**
 * 政府采购 --> 生成资产
 *
 * @author Administrator
 */
@ManagedBean(name = "buildAssetBean")
@SessionScoped
public class BuildAssetBean implements Serializable {

    private final DaoManager daom = DaoConfig.getDaoManager();
    private final ProcureExecEditDao execEditDao = (ProcureExecEditDao) daom.getDao(ProcureExecEditDao.class);
    //
    private List<Asset> assetli = null;//已有资产列表
    private DataModel<CateEditDetail> execModel = new ListDataModel<CateEditDetail>();//已通过审核的采购物品列表
    private List<Asset> saveli = null;
    private ExecuteAppend exappend = null;
    private AssetGBCode node = null;//国标码
    private Map<String, String> gbMap = null;
    private int rowIndex = -1;//行号
    private boolean editStatus = false;
    //
    private String updateLabel = "";
    private String updateValue = "";

    public BuildAssetBean() {
        initGBCodeAndCategoryMap();
        initExecli();
    }

    public void queryAssetli() {
        initAssetli();
    }

    public void queryExecli() {
        initExecli();
    }
    
    public void updateProperty(){
        if(updateLabel.isEmpty() || updateValue.isEmpty() || saveli == null || saveli.isEmpty())return;
        if("name".equals(updateLabel)){            
            for(Asset row:saveli){
                if(row.isSelected())row.setAssetName(updateValue);
            }
        }else if("model".equals(updateLabel)){
            for(Asset row:saveli){
                if(row.isSelected())row.setModel(updateValue);
            }
        }else if("price".equals(updateLabel)){
            for(Asset row:saveli){
                if(row.isSelected())row.setPrice(Double.parseDouble(updateValue.trim()));
            }
        } else if("brand".equals(updateLabel)){            
            for(Asset row:saveli){
                if(row.isSelected())row.setBrand(updateValue);
            }
        } else if("manufacture".equals(updateLabel)){
            for(Asset row:saveli){
                if(row.isSelected())row.setManufacture(updateValue);
            }
        }
    }
    

    private void initGBCodeAndCategoryMap() {
        SqlMapClient client = IbatisTemplate.getSqlMapClient();
        try {
            client.startTransaction();
            
            Map map = new HashMap();
            map.put("orgCode",LoginParam.getOrg().getCode());
            gbMap = client.queryForMap("assetGBCode.queryListAssetGBCode_categoryMap", null, "key", "value");
            
            client.commitTransaction();
        } catch (SQLException ex) {
            try {
                client.endTransaction();
            } catch (SQLException ex1) {
                Logger.getLogger(BuildAssetBean.class.getName()).log(Level.SEVERE, null, ex1);
            }
            Logger.getLogger(BuildAssetBean.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void initAssetli() {
        //初始化 已有资产列表
        Map map = new HashMap();
        map.put("orgCode", LoginParam.getOrg().getCode());
        map.put("iyear", LoginParam.getIyear());
        assetli = IbatisTemplate.queryForList("psncard.queryForAssetDeal", map);
        System.out.println("assetli : " + assetli.size());
    }

    private void initExecli() {
        //初始化 审核通过的 采购列表
        CateEditDetail param = new CateEditDetail();
        param.setOrgCode(LoginParam.getOrg().getCode());
        param.setIyear(iyear());
        param.setStatus("3");
        List<CateEditDetail> execli = IbatisTemplate.queryForList("procureExec.queryListCateDetailByNumber_toAsset", param);
        execModel.setWrappedData(execli);
        System.out.println("execli : " + execli.size());
    }

    public void addExeAppend() {
        CateEditDetail row = execModel.getRowData();
        if(!row.getApp().getContent1().isEmpty() || !row.getApp().getContent2().isEmpty() || !row.getApp().getContent3().isEmpty() || !row.getApp().getContent4().isEmpty()) return;
        ExecuteAppend param = new ExecuteAppend();
        param.setAnumber(row.getAnumber());
        exappend = execEditDao.queryExecuteAppend(param);
        if (exappend == null) {
            exappend = new ExecuteAppend();
        }
        row.setApp(exappend);
    }

    public DataModel<CateEditDetail> getExecModel() {
        if (execModel == null) {
            execModel = new ListDataModel<CateEditDetail>();
            initExecli();
        }
        return execModel;
    }

    private Integer iyear() {
        return LoginParam.getIyear();
        //return 2012;
    }

    public void buildAsset() {
        Integer maxCode = maxCode();
        saveli = new ArrayList<Asset>();
        for (CateEditDetail row : execModel) {
            if (row.isSelected()) {
                for (int i = 0; i < row.getCate().getCount(); i++) {
                    String assetCode = codeFormat(++maxCode);
                    Asset asset = createAsset(row, assetCode);
                    saveli.add(asset);
                }
            }
        }
    }

    public void save() {
        boolean ok = true;
        SqlMapClient client = IbatisTemplate.getSqlMapClient();
        try {
            client.startTransaction();
            client.startBatch();
            for (CateEditDetail row : execModel) {
                if (row.isSelected()) {
                    row.setToAsset(1);//该条目已生成资产,不在出现在待选列表
                    client.update("procureExec.updateExecDetail_toAsset", row);
                }
            }
            for (Asset asset : saveli) {                
                client.insert("psncard.deleteAsset", asset);
                client.insert("psncard.insertAsset", asset);
            }
            client.executeBatch();
            client.commitTransaction();
        } catch (SQLException ex) {
            ok = false;
            try {
                client.endTransaction();
            } catch (SQLException ex1) {
                Logger.getLogger(BuildAssetBean.class.getName()).log(Level.SEVERE, null, ex1);
            }
            Logger.getLogger(BuildAssetBean.class.getName()).log(Level.SEVERE, null, ex);
        }
        if (ok) {
            ToolKit.msgs_info(FacesContext.getCurrentInstance(), null, "资产已生成！");
        } else {
            ToolKit.msgs_info(FacesContext.getCurrentInstance(), null, "生成失败！");
        }
    }

    private Asset createAsset(CateEditDetail data, String assetCode) {
        CateEditBase paramBase = new CateEditBase();
        paramBase.setOrgCode(LoginParam.getOrg().getCode());
        paramBase.setIyear(LoginParam.getIyear());
        paramBase.setNumber(data.getNumber());
        CateEditBase base = execEditDao.queryCateBaseByNumber(paramBase);
        
        System.out.println("base : " + base);
        
//        ExecuteAppend param = new ExecuteAppend();
//        param.setAnumber(data.getAnumber());
//        ExecuteAppend app = execEditDao.queryExecuteAppend(param);
        
         ExecuteAppend app = data.getApp();
         
        System.out.println("app : " + app);
        
        Asset asset = new Asset();
        asset.setOrgCode(LoginParam.getOrg().getCode());
        asset.setClassCode(gbMap.get(data.getCate().getCode()).split("_")[0]);
        asset.setClassName(gbMap.get(data.getCate().getCode()).split("_")[1]);
        asset.setAssetCode(assetCode);
        asset.setAssetName(app.getContent1());
        asset.setModel(app.getContent4());
        
        Double financial = data.getFinancial() == null ? 0d : data.getFinancial();
        Double other = data.getOther() == null ? 0d : data.getOther();
        Double count = new Double(data.getCate().getCount() == null ? 0d : data.getCate().getCount());
        
        System.out.println("financial : " + financial);
        System.out.println("other : " + other);
        System.out.println("count : " + count);
        
        asset.setPrice((financial + other) / count);
        asset.setBrand(app.getContent2());
        asset.setManufacture(app.getContent3());
        asset.setPurchDate(app.getDate1());
        asset.setShelfLife(app.getDate2());
        asset.getDept().setCode(base.getDeptCode());
        asset.getDept().setName(base.getDeptName());
        System.out.println("deptCode : " + base.getDeptCode());
        System.out.println("deptName : " + base.getDeptName());
        asset.getPerson().setCpsn_number(base.getEditPerCode());
        asset.getPerson().setCpsn_name(base.getEditPerName());
        asset.getKeeper().setCpsn_number(base.getEditPerCode());
        asset.getKeeper().setCpsn_name(base.getEditPerName());
        asset.setUseStatus("0");
        asset.setMemo("");
        return asset;
    }

    public Integer maxCode() {
        String orgCode = LoginParam.getOrg().getCode();
        Integer maxCode = (Integer) IbatisTemplate.query("psncard.queryMaxAssetCode", orgCode);
        if (maxCode == null) {
            maxCode = 0;
        }
        return maxCode;
    }

    private String codeFormat(Integer code) {
        return String.format("%08d%n", code).trim();
    }

    public void selected(TreeSelectionChangeEvent event) {
        node = (AssetGBCode) TreeUtil.listener(event);
    }    
    public void changeClassCode() {
        Asset row = saveli.get(rowIndex);
        row.setClassCode(node.getCode());
        row.setClassName(node.getName());
    }

    public List<Asset> getAssetli() {
        return assetli;
    }

    public void setAssetli(List<Asset> assetli) {
        this.assetli = assetli;
    }

    public ExecuteAppend getExappend() {
        return exappend;
    }

    public void setExappend(ExecuteAppend exappend) {
        this.exappend = exappend;
    }

    public boolean isEditStatus() {
        return editStatus;
    }

    public void setEditStatus(boolean editStatus) {
        this.editStatus = editStatus;
    }

    public List<Asset> getSaveli() {
        return saveli;
    }

    public void setSaveli(List<Asset> saveli) {
        this.saveli = saveli;
    }

    public int getRowIndex() {
        return rowIndex;
    }

    public void setRowIndex(int rowIndex) {
        this.rowIndex = rowIndex;
    }

    public AssetGBCode getNode() {
        return node;
    }

    public void setNode(AssetGBCode node) {
        this.node = node;
    }

    public String getUpdateLabel() {
        return updateLabel;
    }

    public void setUpdateLabel(String updateLabel) {
        this.updateLabel = updateLabel;
    }

    public String getUpdateValue() {
        return updateValue;
    }

    public void setUpdateValue(String updateValue) {
        this.updateValue = updateValue;
    }
}
